package com.work.yshop.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.work.yshop.R;
import com.work.yshop.adapter.ProductAdapter;
import com.work.yshop.model.Product;
import com.work.yshop.mvp.contract.SellerHomeContract;
import com.work.yshop.mvp.presenter.SellerHomePresenter;
import com.work.yshop.ui.activity.OrderManageActivity;
import com.work.yshop.ui.activity.ProductDetailActivity;
import com.work.yshop.ui.activity.ProductEditActivity;
import com.work.yshop.ui.activity.ProductListActivity;
import com.work.yshop.ui.activity.PublishProductActivity;

import java.util.List;

/**
 * 卖家首页Fragment
 */
public class SellerHomeFragment extends Fragment implements SellerHomeContract.View {
    
    private static final String TAG = "SellerHomeFragment";
    
    private View rootView;
    private TextView tvSalesAmount, tvProductCount, tvOrderCount;
    private CardView cardProducts, cardOrders, cardPublish;
    private RecyclerView recyclerViewRecentProducts;
    private ProductAdapter adapter;
    private SellerHomeContract.Presenter presenter;
    
    public static SellerHomeFragment newInstance() {
        return new SellerHomeFragment();
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_seller_home, container, false);
        return rootView;
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initPresenter();
        initViews();
        setupListeners();
        
        // 加载数据
        presenter.loadData();
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时重新加载数据，确保显示最新状态
        presenter.loadData();
    }
    
    private void initPresenter() {
        presenter = new SellerHomePresenter(getContext());
        presenter.attachView(this);
    }
    
    private void initViews() {
        // 销售额统计
        tvSalesAmount = rootView.findViewById(R.id.tv_sales_amount);
        tvProductCount = rootView.findViewById(R.id.tv_product_count);
        tvOrderCount = rootView.findViewById(R.id.tv_order_count);
        
        // 功能卡片
        cardProducts = rootView.findViewById(R.id.card_products);
        cardOrders = rootView.findViewById(R.id.card_orders);
        cardPublish = rootView.findViewById(R.id.card_publish);
        
        // 最近上架商品列表
        recyclerViewRecentProducts = rootView.findViewById(R.id.recycler_view_recent_products);
        recyclerViewRecentProducts.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ProductAdapter();
        
        // 设置商品点击事件
        adapter.setOnItemClickListener(position -> {
            Product product = adapter.getItem(position);
            Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
            intent.putExtra("product_id", product.getId());
            startActivity(intent);
        });
        
        // 设置编辑点击事件
        adapter.setOnEditClickListener(position -> {
            Product product = adapter.getItem(position);
            presenter.editProduct(product);
        });
        
        // 设置上下架点击事件
        adapter.setOnToggleStatusClickListener(position -> {
            Product product = adapter.getItem(position);
            showToggleStatusConfirmDialog(product);
        });
        
        recyclerViewRecentProducts.setAdapter(adapter);
    }
    
    private void setupListeners() {
        // 我的货品点击事件
        cardProducts.setOnClickListener(v -> presenter.navigateToProductList());
        
        // 订单管理点击事件
        cardOrders.setOnClickListener(v -> presenter.navigateToOrderManage());
        
        // 发布商品点击事件
        cardPublish.setOnClickListener(v -> presenter.navigateToPublishProduct());
    }
    
    /**
     * 显示切换商品状态确认对话框
     */
    private void showToggleStatusConfirmDialog(Product product) {
        if (getContext() == null) return;
        
        // 确认对话框
        String message = product.getStatus() == 1 ? 
                "确定要下架商品 \"" + product.getName() + "\" 吗？" : 
                "确定要上架商品 \"" + product.getName() + "\" 吗？";
        
        new AlertDialog.Builder(getContext())
                .setTitle("确认操作")
                .setMessage(message)
                .setPositiveButton("确定", (dialog, which) -> {
                    presenter.toggleProductStatus(product);
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    @Override
    public void showLoading() {
        // 可以添加加载进度条
    }
    
    @Override
    public void hideLoading() {
        // 隐藏加载进度条
    }
    
    @Override
    public void showError(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void showProductCount(int count) {
        tvProductCount.setText(String.valueOf(count));
    }
    
    @Override
    public void showProducts(List<Product> products) {
        adapter.setData(products);
    }
    
    @Override
    public void showSalesAmount(String amount) {
        tvSalesAmount.setText(amount);
    }
    
    @Override
    public void showOrderCount(String count) {
        tvOrderCount.setText(count);
    }
    
    @Override
    public void showSuccess(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void navigateToProductEdit(int productId) {
        Intent intent = new Intent(getActivity(), ProductEditActivity.class);
        intent.putExtra("product_id", productId);
        startActivity(intent);
    }
    
    @Override
    public void navigateToProductList() {
        Intent intent = new Intent(getActivity(), ProductListActivity.class);
        startActivity(intent);
    }
    
    @Override
    public void navigateToOrderManage() {
        Intent intent = new Intent(getActivity(), OrderManageActivity.class);
        startActivity(intent);
    }
    
    @Override
    public void navigateToPublishProduct() {
        Intent intent = new Intent(getActivity(), PublishProductActivity.class);
        startActivity(intent);
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.detachView();
        }
        rootView = null;
    }
} 